<template>
  <div style="margin-top: 20px">
    <div class="my-btn" >
      <a-button type="primary" @click="() => {this.$refs.form.dialog = true}">
        添加培养方案
      </a-button>
    </div>
    <a-table :columns="columns"
             rowKey="id"
             :expandedRowKeys="expandedRowKeys"
             :data-source="data"
             class="components-table-demo-nested"
             @expand="expand"
             :pagination="false"
             :bordered="true">

      <template slot="grade" slot-scope="record">
        <span v-text="gradeStr(record.gradeId)"></span>
      </template>
      <template slot="major" slot-scope="record">
        <span v-text="majorStr(record.majorId)"></span>
      </template>
      <template slot="operation" slot-scope="text, record">
        <a-button type="primary" @click="() => deployApplication(record)" >
          复制方案
        </a-button>
      </template>
      <a-table
          slot="expandedRowRender"
          :columns="innerColumns"
          :data-source="dataSource"
          :pagination="false"
          id="innerTable"
          :bordered="true">

              <template
                  v-for="col in ['theoretical', 'experimental', 'credit']"
                  :slot="col"
                  slot-scope="text, record"
              >
                <div :key="col">
                  <a-input
                      v-if="record.id == editingKey"
                      style="width: 100px"
                      :value="text"
                      @change="e => handleChange(e.target.value, record.id, col)"
                  />
                  <template v-else>
                    {{ text }}
                  </template>
                </div>
              </template>
              <template slot="course" slot-scope="record">
                <template v-if="record.id == editingKey">
                  <a-select
                      showSearch
                      :filter-option="filterOption"
                      @change="selectChange(record.id, 'courseId', courseId)"
                      style="width: 100px"
                      v-model="courseId"
                      placeholder="请选择课程名">
                    <a-select-option
                        v-for="course in courses"
                        :key="course.id"
                        :value="course.id"
                    >{{course.name}}</a-select-option>
                  </a-select>
                </template>
                <span v-else v-text="courseStr(record.courseId)"></span>
              </template>
              <template slot="method" slot-scope="record">
                <template v-if="record.id == editingKey">
                  <a-select
                      showSearch
                      :filter-option="filterOption"
                      @change="selectChange(record.id, 'method', methodId)"
                      style="width: 100px"
                      v-model="methodId"
                      placeholder="请选择考核方式">
                    <a-select-option value="0">考察</a-select-option>
                    <a-select-option value="1">考试</a-select-option>
                  </a-select>
                </template>
                <span v-else v-text="record.method == 0 ? '考察' : '考试'"></span>
              </template>
              <template slot="term" slot-scope="record">
                <template v-if="record.id == editingKey">
                  <a-select
                      showSearch
                      :filter-option="filterOption"
                      @change="selectChange(record.id, 'term', term)"
                      style="width: 100px"
                      v-model="term"
                      placeholder="请选择学期">
                    <a-select-option
                        v-for="value in terms"
                        :key="value"
                        :value="value"
                    >{{value}}</a-select-option>

                  </a-select>
                </template>
                <span v-else v-text="record.term"></span>
              </template>
              <template slot="status" slot-scope="record">
                <a-tag :color="record.status === 0 ? 'red' : 'green'">
                  <span v-text="record.status === 0 ? '未完成' : '已完成'"></span>
                </a-tag>
              </template>
              <template slot="operation" slot-scope="text, record">
                <div class="editable-row-operations">
                <span v-if="record.id == editingKey">
                  <a @click="() => save(record.id)">保存</a>
                  <a-divider type="vertical" />
                  <a-popconfirm title="确认取消?" @confirm="() => cancel(record.id)">
                    <a>取消</a>
                  </a-popconfirm>
                </span>
                  <span v-else>
                  <a :disabled="editingKey !== ''" @click="() => edit(record.id)">修改</a>
                  <a-divider type="vertical" />
                  <a-popconfirm title="确认删除?" @confirm="() => delProgram(record.id)">
                    <a>删除</a>
                  </a-popconfirm>
                </span>
                </div>
              </template>
      </a-table>
    </a-table>
    <div class="pagination">
      <a-pagination
          v-model="pageParam.current"
          show-size-changer
          :page-size.sync="pageParam.pageSize"
          :total="pageParam.total"
          @showSizeChange="onShowSizeChange"
          @change="onPageChange"
      />
    </div>
    <programForm ref="form"
                 :grades="grades"
                 :courses="courses"
                 :majors="majors"
                 :terms="terms"
                 @success="refreshData"/>
    <copyForm ref="copyForm"
              :grades="grades"
              :majors="majors"
              :old-grade="oldGrade"
              :old-major="oldMajor"
              @success="refreshData"/>
  </div>
</template>
<script>

import ProgramForm from "@/pages/allocation/program/components/ProgramForm";
import CopyForm from "@/pages/allocation/program/components/CopyForm";
import {totalGrade} from "@/services/grade";
import {totalMajor} from "@/services/major";
import {totalCourse} from "@/services/course";
import {editProgram, deleteProgram, listProgramByPage, details} from "@/services/program";

const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      scopedSlots: { customRender: 'id' },
    },
    {
      title: '年级',
      key: 'gradeId',
      scopedSlots: { customRender: 'grade' },
    },
    {
      title: '专业',
      key: 'majorId',
      scopedSlots: { customRender: 'major' },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: '12%',
      scopedSlots: { customRender: 'operation' },
    },
]

const innerColumns = [
  {
    title: 'id',
    dataIndex: 'id',
    scopedSlots: { customRender: 'id' },
  },
  {
    title: '课程名称',
    key: 'courseId',
    scopedSlots: { customRender: 'course' },
  },
  {
    title: '理论学时',
    dataIndex: 'theoretical',
    scopedSlots: { customRender: 'theoretical' },
  },
  {
    title: '实验学时',
    dataIndex: 'experimental',
    scopedSlots: { customRender: 'experimental' },
  },
  {
    title: '学分',
    dataIndex: 'credit',
    scopedSlots: { customRender: 'credit' },
  },
  {
    title: '考核方式',
    key: 'method',
    scopedSlots: { customRender: 'method' },
  },
  {
    title: '对应学期',
    key: 'term',
    scopedSlots: { customRender: 'term' },
  },
  {
    title: '分配状态',
    key: 'status',
    scopedSlots: { customRender: 'status' },
  },

  {
    title: '操作',
    dataIndex: 'operation',
    // width: '12%',
    scopedSlots: { customRender: 'operation' },
  },

]
export default {
  components: { ProgramForm, CopyForm },
  data() {
    return {
      pageParam :{
        pageSize: 10,
        current: 1,
        total: 200,
      },
      data: [],
      dataSource: [],
      cacheData: [],
      columns,
      innerColumns,
      oldMajor: '',
      oldGrade: '',
      editingKey: '',
      expandedRowKeys: [],//控制显示子表格
      grades: [],
      majors: [],
      courses: [],
      gradeId: 0,
      majorId: 0,
      courseId: 0,
      methodId: 0,
      term: 0,
      terms: [1,2,3,4,5,6,7,8]
    };
  },

  methods: {
    delProgram(key){
      deleteProgram(key).then(res => {
        if (res.data.code == 200){
          this.$success = "删除成功"
          this.expandedRowKeys = []
          this.refreshData()
        } else {
          this.$error = '删除失败'
        }
      })
    },
    handleChange(value, key, column) {
      const newData = this.dataSource;
      const target = newData.find(item => key === item.id);
      if (target) {
        target[column] = value;
        this.dataSource = newData;
      }
    },
    edit(key) {
      const newData = this.dataSource;
      const target = newData.find(item => key === item.id);
      // this.gradeId = target.gradeId
      this.courseId = target.courseId
      // this.majorId = target.majorId
      this.methodId = target.method
      this.term = target.term
      if (target) {
        this.editingKey = key;
      }
    },
    save(key) {
      const newData = this.dataSource;
      const newCacheData = this.cacheData;
      const target = newData.find(item => key === item.id);
      const targetCache = newCacheData.find(item => key === item.id);
      if (target && targetCache) {
        console.log(target)
        editProgram(target).then(res => {
          if (res.data.code == 200){
            this.$success = "修改成功"
          } else {
            this.$error = '修改失败'
          }
        })
        Object.assign(targetCache, target);
        this.cacheData = newCacheData;
      }
      this.editingKey = '';
    },
    cancel(key) {
      const newData = this.dataSource;
      const target = newData.find(item => key === item.id);
      this.editingKey = '';
      if (target) {
        Object.assign(target, this.cacheData.find(item => key === item.id));
        // this.data = newData;
      }
    },

    deployApplication(program) {
      this.oldMajor = program.majorId
      this.oldGrade = program.gradeId
      this.$refs.copyForm.dialog = true;
    },
    refreshData() {
      this.onPageChange(this.pageParam.current, this.pageParam.pageSize )
    },

    onShowSizeChange(current, pageSize) {
      listProgramByPage(current, pageSize).then(this.afterChange)
    },
    onPageChange(page, pageSize) {
      listProgramByPage(page, pageSize).then(this.afterChange)
    },
    afterChange(res) {
      const changeRes = res.data
      if (changeRes.code == 200){
        const pageRes = changeRes.data
        this.pageParam.current = pageRes.current
        this.pageParam.pageSize = pageRes.size
        this.pageParam.total = pageRes.total
        this.data = pageRes.records
        // this.cacheData = this.dataSource.map(item => ({ ...item }));
      } else {
        this.$message.error = changeRes.message
      }
    },

    //展开节点操作
    expand(expanded, record) {
      this.expandedRowKeys = []
      if (expanded) {
        if (record){
          this.expandedRowKeys = [record.id];
        }
        details(record.gradeId, record.majorId).then(res => {
          const result = res.data
          if (result.code == 200) {
            this.dataSource = result.data
            this.cacheData = this.dataSource.map(item => ({ ...item }));
          } else {
            this.$message.error(result.message)
          }
        })
      }
    },

    listTotalGrade() {
      totalGrade().then(res => {
        const result = res.data
        if (result.code == 200) {
          this.grades = result.data
        } else {
          this.$message.error(result.message)
        }
      })
    },
    listTotalMajor() {
      totalMajor().then(res => {
        const result = res.data
        if (result.code == 200) {
          this.majors = result.data
        } else {
          this.$message.error(result.message)
        }
      })
    },
    listTotalCourse() {
      totalCourse().then(res => {
        const result = res.data
        if (result.code == 200) {
          this.courses = result.data
        } else {
          this.$message.error(result.message)
        }
      })
    },

    gradeStr(gradeId) {
      const grades = this.grades
      const grade = grades.find(item => item.id === gradeId);
      return grade.grade
    },
    majorStr(majorId) {
      const majors = this.majors
      const major = majors.find(item => item.id === majorId)
      return major.name
    },
    courseStr(courseId) {
      const courses = this.courses
      const course = courses.find(item => item.id === courseId)
      return course.name
    },
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    selectChange(key, column, value) {
      console.log(key, column, value)
      const newData = this.dataSource;
      const target = newData.find(item => key === item.id);
      if (target) {
        target[column] = value;
        this.dataSource = newData;
        console.log(newData)
      }
    },
  },
  created() {
    this.refreshData()
    this.listTotalGrade()
    this.listTotalMajor()
    this.listTotalCourse()
  }
};
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.my-btn {
  text-align: right;
  margin-right: 10px;
  margin-bottom: 10px;
}

</style>
